import { ElMessageBox, ElMessage } from "element-plus"
import { useStore } from "@/store/index"
import { TreeType } from "../type"
import { Ref, toRaw } from "vue-demi"
import http from "@/utils/http"
import { TreeToFlat } from "@/utils/format"

function useDltFile(treeRef: Ref<TreeType>) {
  const store = useStore()
  const dltFile = (id: number) => {
    const idArr = TreeToFlat(
      [toRaw(treeRef.value?.store.nodesMap[id])],
      "childNodes"
    ).map((item) => {
      return item.id
    })
    if (store.state.user.id !== treeRef.value?.store.nodesMap[id].data.userId) {
      ElMessage.warning("无法删除别人的文档")
    }
    ElMessageBox.confirm("删除后不可恢复，你确定要删除吗?", "Warning", {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      type: "warning",
    })
      .then(async () => {
        const res = await http.post("/file/dltFile", { idArr })
        if (res.code === 1) {
          if (id === store.state.markdown.id) {
            store.commit("markdown/clearMarkdown")
          }
          ElMessage.info("文件已删除")
          await store.dispatch("fileTree/getFile")
        } else {
          ElMessage.error(res.msg)
        }
      })
      .catch(() => {})
    // const res = await this.
  }
  return { dltFile }
}
export default useDltFile
